package com.wuyou.service.impl;

import com.wuyou.domain.bo.AdvTypeBO;
import com.wuyou.domain.po.AdvType;
import com.wuyou.domain.po.Advertising;
import com.wuyou.mapper.AdvTypeMapper;
import com.wuyou.mapper.AdvertisingMapper;
import com.wuyou.service.IAdvTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 刘雷雨
 * @since 2022-09-29
 */
@Service
public class AdvTypeServiceImpl extends ServiceImpl<AdvTypeMapper, AdvType> implements IAdvTypeService {

    @Autowired
    private AdvTypeMapper advTypeMapper;

    @Autowired
    private AdvertisingMapper advertisingMapper;

    @Override
    public List<AdvTypeBO> getAdvTypeList() {

        List<AdvType> advTypes = advTypeMapper.selectList(null);
        List<AdvTypeBO> advTypeBOs = new ArrayList<>();
        AdvTypeBO advTypeBO = new AdvTypeBO();
        BeanUtils.copyProperties(advTypes.get(0),advTypeBO);
        advTypeBOs.add(advTypeBO);
        long now = new Date().getTime();
        //获取广告栏位剩余栏位
        Integer surplusRegion = advTypeBOs.get(0).getSurplusRegion();
        //判断还有没有剩余栏位
        if (surplusRegion == 0) {
            List<Advertising> advertisings = advertisingMapper.selectList(null);
            for (int i = 0; i < advertisings.size(); i++) {
                //投放结束时间
                long end = advertisings.get(i).getEndTime().getTime();
                long differ = end - now;
                if (differ < now) {
                    now=differ;
                    advTypeBOs.get(i).setTime(new Date(end));
                }
            }
            return advTypeBOs;
        }
        return advTypeBOs;
    }

    //修改广告栏位信息
    @Override
    public void updateAdvRegion(Integer advTypeIds,String flag) {
        AdvType updateAdvType = advTypeMapper.selectById(advTypeIds);
        if ("1".equals(flag)) { //1 = 使用栏位
            updateAdvType.setUseRegion(updateAdvType.getUseRegion() + 1);
            updateAdvType.setSurplusRegion(updateAdvType.getSurplusRegion() - 1);
        }else {
            updateAdvType.setUseRegion(updateAdvType.getUseRegion() - 1);
            updateAdvType.setSurplusRegion(updateAdvType.getSurplusRegion() + 1);
        }
        advTypeMapper.updateById(updateAdvType);
    }
}
